package com.lysj.print.print.controller;

import com.lysj.admin.utils.json.JacksonUtil;
import com.lysj.admin.utils.web.Resp;
import com.lysj.print.print.domain.PrinterRotation;
import com.lysj.print.print.service.PrinterRotationService;
import com.lysj.print.print.service.PrinterService;
import com.lysj.print.print.vo.OrderItemVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 11:30 2019/3/19
 * @ Description:
 **/
@Slf4j
@RestController
@RequestMapping("/printer/management")
public class PrintManagementController {

    @Resource
    private PrinterService printerService;

    @Resource
    private PrinterRotationService printerRotationService;


    private static final String URL = "http://api.feieyun.cn/Api/Open/";//不需要修改
    private static final String USER = "691617970@qq.com";//*必填*：账号名
    private static final String UKEY = "DV3S6mU3hw8aZ4AV";//*必填*: 注册账号后生成的UKEY
    private static final String SN = "920508225";//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API

    /*
     * @author drj
     * @date 2019-03-20 16:27
     * @Description:获取对应门店的打印机列表
     */
    @GetMapping("/select_item")
    public Resp selectItem(String storeId) {
        return new Resp().success(printerService.getRepository().selectItems(storeId));
    }

    /*
     * @author drj
     * @date 2019-03-22 15:05
     * @Description :打印机轮训接口(除了飞鹅)
     */
    @GetMapping("/training_rotation")
    public Resp trainingRotation(String printerId) {
        List<PrinterRotation> printerRotationList = printerRotationService.getRepository().
                findByPrinterIdAndStatusAndDataType(printerId, PrinterRotation.Status.UNPRINT.getCode(), PrinterRotation.DataType.OTHER.getCode());
        return new Resp().success(printerRotationList);
    }


    @PostMapping("/call_back")
    public Resp callBack(String printerRotationId) {
        PrinterRotation printerRotation = printerRotationService.findOne(printerRotationId);
        //改变轮训打印状态
        printerRotation.setStatus(PrinterRotation.Status.SUCCESSPRINT.getCode());
        printerRotationService.getRepository().save(printerRotation);
        return new Resp().success("回调成功");
    }


    /*
     * @author drj
     * @date 2019-03-19 11:26
     * @Description :提供打印
     */
    @PostMapping("/print_provide")
    public Resp printProvide() {
        List<OrderItemVo> orderItemVoList = new LinkedList<>();
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setFoodName("饭");
        orderItemVo.setSellPrice(new BigDecimal("1"));
        orderItemVo.setAmount(11);
        orderItemVo.setSubtotal(new BigDecimal("11"));
        orderItemVoList.add(orderItemVo);
        OrderItemVo orderItemVo1 = new OrderItemVo();
        orderItemVo1.setFoodName("蛋炒饭");
        orderItemVo1.setSellPrice(new BigDecimal("22"));
        orderItemVo1.setAmount(12);
        orderItemVo1.setSubtotal(new BigDecimal("22"));
        orderItemVoList.add(orderItemVo1);
        OrderItemVo orderItemVo2 = new OrderItemVo();
        orderItemVo2.setFoodName("番茄蛋炒饭");
        orderItemVo2.setSellPrice(new BigDecimal("44"));
        orderItemVo2.setAmount(13);
        orderItemVo2.setSubtotal(new BigDecimal("44"));
        orderItemVoList.add(orderItemVo2);
        OrderItemVo orderItemVo3 = new OrderItemVo();
        orderItemVo3.setFoodName("西红柿炒鸡蛋");
        orderItemVo3.setSellPrice(new BigDecimal("55"));
        orderItemVo3.setAmount(14);
        orderItemVo3.setSubtotal(new BigDecimal("55"));
        orderItemVoList.add(orderItemVo3);
        OrderItemVo orderItemVo4 = new OrderItemVo();
        orderItemVo4.setFoodName("漳州大侠");
        orderItemVo4.setSellPrice(new BigDecimal("66"));
        orderItemVo4.setAmount(16);
        orderItemVo4.setSubtotal(new BigDecimal("16"));
        orderItemVoList.add(orderItemVo4);


        String content;
        content = "<CB>测试打印</CB><BR>";
        content += "名称　　　　　 单价  数量 金额<BR>";
        content += "--------------------------------<BR>";
        for (OrderItemVo itemVo : orderItemVoList) {
            content += itemVo.getFoodName() + "　　　　　　 " + itemVo.getSellPrice() + "    "
                    + itemVo.getAmount() + "   " + itemVo.getSubtotal() + "<BR>";
        }
        content += "饭　　　　　　 1.0    1   1.0<BR>";
        content += "炒饭　　　　　 10.0   10  10.0<BR>";
        content += "蛋炒饭　　　　 10.0   10  100.0<BR>";
        content += "鸡蛋炒饭　　　 100.0  1   100.0<BR>";
        content += "番茄蛋炒饭　　 1000.0 1   100.0<BR>";
        content += "西红柿蛋炒饭　 1000.0 1   100.0<BR>";
        content += "西红柿鸡蛋炒饭 100.0  10  100.0<BR>";


        content += "备注：加辣<BR>";
        content += "--------------------------------<BR>";
        content += "合计：xx.0元<BR>";
        content += "送货地点：广州市南沙区xx路xx号<BR>";
        content += "联系电话：13888888888888<BR>";
        content += "订餐时间：2016-08-08 08:08:08<BR>";
        content += "<QR>http://www.dzist.com</QR>";
        System.out.println(content);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", SN));
        nvps.add(new BasicNameValuePair("content", content.toString()));
        nvps.add(new BasicNameValuePair("times", "1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> map = JacksonUtil.toObjectMap(result);
        if (map.get("ret").equals(0)) {
            System.out.println("打印成功");
        } else {
            System.out.println("打印失败");
        }
        return new Resp().success(map);
    }


    //生成签名字符串
    private static String signature(String USER, String UKEY, String STIME) {
        String s = DigestUtils.sha1Hex(USER + UKEY + STIME);
        return s;
    }
}
